package com.wxhntmy.google.v2;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.wxhntmy.config.Oauth2;
import com.wxhntmy.config.ProjectConfig;
import com.wxhntmy.config.TranslateV2;
import com.wxhntmy.google.oauth2.GoogleTranslateOauth2ByJsonUtil;
import com.wxhntmy.google.oauth2.GoogleTranslateOauth2Util;
import com.wxhntmy.httpclient.RestMockByProxy;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * Google Translate V2 Utils
 *
 * @author chenwc
 * @date 2024/7/30
 */
public class GoogleTranslateV2Utils {
    private static final Logger logger = LoggerFactory.getLogger(GoogleTranslateV2Utils.class);
    private static final ProjectConfig PROJECT_CONFIG = ProjectConfig.getInstance();
    private static final Oauth2 OAUTH_2 = PROJECT_CONFIG.getGoogle().getOauth2();
    private static final TranslateV2 TRANSLATE_V_2 = PROJECT_CONFIG.getGoogle().getTranslate().getV2();

    /**
     * 翻译单个文本
     *
     * @param text           待翻译的文本
     * @param targetLanguage 目标语言
     * @return 翻译结果
     */
    public static String translateText(String text, String targetLanguage) {
        return translateBatchText(new LinkedList<>(List.of(text)), targetLanguage).get(text);
    }

    /**
     * 翻译多个文本
     *
     * @param text           待翻译的文本，需要有顺序的list
     * @param targetLanguage 目标语言
     * @return 翻译结果
     */
    public static Map<String, String> translateBatchText(LinkedList<String> text, String targetLanguage) {
        JSONObject sendJson = new JSONObject();
        sendJson.put("q", text);
        sendJson.put("target", targetLanguage);

        logger.info("请求报文: {}", sendJson.toJSONString());
        Map<String, String> headers = getHeaders();
        headers.put("Content-Type", "application/json");
        logger.debug("请求头: {}", JSON.toJSONString(headers));

        String result = RestMockByProxy.sendPostByBody(TRANSLATE_V_2.getTranslateTextUrl(), headers, sendJson.toJSONString());
        JSONObject resultJson = JSONObject.parseObject(result);
        logger.info("响应报文: {}", resultJson.toJSONString());
        JSONObject data = resultJson.getJSONObject("data");
        Map<String, String> resultMap = new HashMap<>();
        if (data != null) {
            JSONArray translations = data.getJSONArray("translations");
            if (translations != null) {
                logger.info("翻译结果: {}", translations.toJSONString());
                for (int i = 0; i < text.size(); i++) {
                    resultMap.put(text.get(i), translations.getJSONObject(i).getString("translatedText"));
                }
            }
        }
        return resultMap;
    }

    /**
     * 获取支持的语言列表
     *
     * @return 支持的语言列表
     */
    public static List<String> listSupportedLanguages() {
        Map<String, String> headers = getHeaders();
        String result = RestMockByProxy.sendGetByParameter(TRANSLATE_V_2.getListLanguagesUrl(), headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        logger.info("响应报文: {}", resultJson.toJSONString());
        JSONArray languages = resultJson.getJSONObject("data").getJSONArray("languages");
        List<String> resultList = new ArrayList<>();
        if (languages != null) {
            for (int i = 0; i < languages.size(); i++) {
                JSONObject language = languages.getJSONObject(i);
                if (language != null) {
                    String languageCode = language.getString("language");
                    if (StringUtils.isNotBlank(languageCode)) {
                        resultList.add(languageCode);
                    }
                }
            }
        }
        return resultList;
    }

    /**
     * 获取支持的语言列表
     *
     * @return 支持的语言列表
     */
    public static JSONObject listSrcLanguageSupportedLanguages(String srcLanguage) {
        Map<String, String> headers = getHeaders();
        JSONObject sendJsonObject = new JSONObject();
        sendJsonObject.put("target", srcLanguage);
        String result = RestMockByProxy.sendPostByBody(TRANSLATE_V_2.getListLanguagesUrl(), headers, sendJsonObject.toJSONString());
        JSONObject resultJson = JSONObject.parseObject(result);
        logger.info("响应报文: " + resultJson.toJSONString());

        return resultJson;
    }

    /**
     * 检测语言
     *
     * @param text 待检测的文本
     * @return 检测结果
     */
    public static List<Map<String, String>> detectLanguage(String text) {
        JSONObject sendJson = new JSONObject();
        sendJson.put("q", text);
        Map<String, String> headers = getHeaders();
        headers.put("Content-Type", "application/json");
        logger.debug("请求头: {}", JSON.toJSONString(headers));

        String result = RestMockByProxy.sendPostByBody(TRANSLATE_V_2.getDetectLanguageUrl(), headers, sendJson.toJSONString());
        JSONObject resultJson = JSONObject.parseObject(result);
        logger.info("响应报文: {}", resultJson.toJSONString());
        JSONObject data = resultJson.getJSONObject("data");
        JSONArray detectedLanguages = data.getJSONArray("detections");
        List<Map<String, String>> resultMapList = new ArrayList<>();
        if (detectedLanguages != null) {
            for (int i = 0; i < detectedLanguages.size(); i++) {
                JSONObject detectedLanguage = detectedLanguages.getJSONArray(0).getJSONObject(i);
                Map<String, String> resultMap = new HashMap<>();
                resultMap.put("language", detectedLanguage.getString("language"));
                resultMap.put("confidence", detectedLanguage.getString("confidence"));
                resultMap.put("isReliable", detectedLanguage.getString("isReliable"));
                resultMapList.add(resultMap);
            }
        }
        return resultMapList;
    }

    /**
     * 获取请求头
     *
     * @return 请求头
     */
    private static Map<String, String> getHeaders() {
        Map<String, String> headers = new HashMap<>();
        if (PROJECT_CONFIG.isUseJsonPrivateKey()) {
            headers.put("Authorization", OAUTH_2.getTokenPrefix() + GoogleTranslateOauth2ByJsonUtil.getAccessToken());
        } else {
            headers.put("Authorization", OAUTH_2.getTokenPrefix() + GoogleTranslateOauth2Util.getAccessToken());
        }

        headers.put("x-goog-user-project", TRANSLATE_V_2.getProjectId());
        headers.put("Host", "translation.googleapis.com");
        headers.put("Accept", "*/*");
        headers.put("Accept-Encoding", "gzip, deflate, br");
        headers.put("Connection", "keep-alive");
        headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36");
        return headers;
    }
}
